package com.ruoyi.app.strategy.factory;

import com.ruoyi.app.domain.entity.User;
import com.ruoyi.app.domain.params.UserLoginParam;
import com.ruoyi.app.domain.enums.LoginTypeEnum;
import com.ruoyi.app.strategy.LoginStrategy;
import com.ruoyi.app.strategy.impl.AccountLoginStrategyImpl;
import com.ruoyi.app.strategy.impl.EmailLoginStrategyImpl;
import com.ruoyi.app.strategy.impl.PhoneLoginStrategyImpl;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Component
public class LoginFactory {

    /**
     * 存放所有登录策略
     */
    private final Map<Long, LoginStrategy> strategies = new HashMap<>();

    /**
     * 通过@Autowired注入所有的LoginStrategy实现
     */
    @Autowired
    public LoginFactory(AccountLoginStrategyImpl accountLoginStrategyImpl,
                        EmailLoginStrategyImpl emailLoginStrategyImpl,
                        PhoneLoginStrategyImpl phoneLoginStrategyImpl) {
        this.strategies.put(LoginTypeEnum.ACCOUNT.getCode(), accountLoginStrategyImpl);
        this.strategies.put(LoginTypeEnum.EMAIL.getCode(), emailLoginStrategyImpl);
        this.strategies.put(LoginTypeEnum.PHONE.getCode(), phoneLoginStrategyImpl);
    }

    /**
     * 根据登录类型选择对应的登录策略
     */
    public User login(UserLoginParam userLoginParam) throws ServiceException {
        LoginStrategy strategy = strategies.get(userLoginParam.getLoginType());
        Optional.ofNullable(strategy).orElseThrow(() -> new ServiceException("登录方式错误", HttpStatus.FORBIDDEN));
        return strategy.login(userLoginParam);
    }
}
